import React, { useEffect, useState } from "react";
import { Space, Table, Tag } from "antd";
import type { TableProps } from "antd";
import instance from "../../api/request";
import type { FormProps } from "antd";
import { Button, Checkbox, Form, Input } from "antd";
import { Modal } from "antd";

function Index() {
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }
  const [data, setData] = useState([]);
  const [total, setTotal] = useState();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState("");
  const [tag, setTag] = useState("");
  const [rest] = Form.useForm();
  const [addForm] = Form.useForm();

  const [flag, setFlag] = useState(false);
  const [id, setId] = useState("");
  const getData = () => {
    const params = { page, pageSize };
    if (title) params.keyword = title;
    if (tag) params.tag = tag;
    instance.get("/article/list", { params }).then((res) => {
      if (res.data.rows) {
        setData(res.data.rows);
        setTotal(res.data.count);
      }
    });
  };
  useEffect(() => {
    getData();
  }, [total, page, pageSize, title, tag]);

  const pageChange = (fenyepage, fenyepageSize) => {
    setPage(fenyepage);
    setPageSize(fenyepageSize);
  };
  type FieldType = {
    keyword?: string;
    tag?: string;
    content?: string;
  };
  const chong = () => {
    rest.resetFields();
    setTitle("");
    setTag("");
    getData();
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    setTitle(values.title);
    setTag(values.tag);
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  const [columns] = useState<TableProps<DataType>["columns"]>([
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },

    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "标签",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? "geekblue" : "green";

            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button>详情</Button>
          <Button onClick={() => bian(record)}>编辑</Button>
        </Space>
      ),
    },
  ]);

  const addonFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    if (flag) {
      instance
        .post(`/article`, {
          ...values,
          tagList: ["HTTP"],
          categoryList: ["HTTP"],
          authorId: 47529555,
        })
        .then(res => {
          console.log(res);
          setIsModalOpen(false);
          getData();
        });
    } else {
      instance
        .put(`/article/${id}`, {
          ...values,
          tagList: ["HTTP"],
          categoryList: ["HTTP"],
        })
        .then((res) => {
          console.log(res);
          setIsModalOpen(false);
          getData();
        });
    }
  };

  const addonFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  const [isModalOpen, setIsModalOpen] = useState(false);
  const zeng = () => {
    setIsModalOpen(true);
    addForm.resetFields();
    setFlag(true);
  };

  const bian = (record) => {
    setFlag(false);
    setIsModalOpen(true);
    addForm.setFieldsValue(record);
    setId(record.id);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <div>
      <Button onClick={zeng}>新增</Button>
      <Modal
        title={flag ? "新增数据" : "编辑数据"}
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          form={addForm}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={addonFinish}
          onFinishFailed={addonFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="标题" name="title">
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="内容" name="content">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Form
        name="basic"
        form={rest}
        labelCol={{ span: 8 }}
        layout="inline"
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 800 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType> label="标题" name="title">
          <Input />
        </Form.Item>

        <Form.Item<FieldType> label="标签" name="tag">
          <Input />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Button onClick={() => chong()}>重置</Button>
      </Form>
      <Table<DataType>
        columns={columns}
        dataSource={data}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: pageChange,
        }}
      />
    </div>
  );
}

export default Index;
